package com.jieshuibao.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.jieshuibao.common.config.Const;
import com.jieshuibao.mapper.ArticleMapper;
import com.jieshuibao.mapper.CmsArticleMapper;
import com.jieshuibao.mapper.QuestionMapper;
import com.jieshuibao.mapper.RedEnvelopesExMapper;
import com.jieshuibao.mapper.RedEnvelopesMapper;
import com.jieshuibao.mapper.UserDealRecordMapper;
import com.jieshuibao.mapper.UserMapper;
import com.jieshuibao.model.db.CountAndSumMoney;
import com.jieshuibao.model.db.QuestionUserKey;
import com.jieshuibao.model.db.RedEnvelopes;
import com.jieshuibao.model.db.RedEnvelopesArticleUser;
import com.jieshuibao.model.db.RedEnvelopesExample;
import com.jieshuibao.model.db.RedEnvelopesExample.Criteria;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.UserDealRecord;
import com.jieshuibao.model.domain.PagePhone;
import com.jieshuibao.model.domain.SendRedResponse;
import com.jieshuibao.util.IdGen;
import com.jieshuibao.util.JsonUtil;
import com.jieshuibao.util.MoneyRandom;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.util.PayCommonUtil;

@Service
public class RedEnvelopesService{
	
	private static final Logger log = Logger.getLogger(RedEnvelopesService.class);
	
	@Resource
	private RedEnvelopesMapper redEnvelopesMapper;
	@Resource
	private RedEnvelopesExMapper redEnvelopesExMapper;
	@Resource
	private ArticleMapper articleMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private CmsArticleMapper cmsArticleMapper;
	@Resource
	private UserDealRecordMapper userDealRecordMapper;
	@Resource
	private RedisService redisService;
	
	@Resource
	private QuestionMapper questionMapper;
	
	@Resource
	private QuestionUserService questionUserService;
	
	@Resource
	private UserService userService;
	@Resource
	private UserDealRecordService userDealRecordService;
	
	
	public void addRedEnvelopes(RedEnvelopes redEnvelopes) {
		redEnvelopesMapper.insertSelective(redEnvelopes);
	}
	
	public void delRedEnvelopesByUuid(String uuid) {
		redEnvelopesMapper.deleteByPrimaryKey(uuid);
	}
	
	public void updateRedEnvelopes(RedEnvelopes redEnvelopes) {
		redEnvelopesMapper.updateByPrimaryKeySelective(redEnvelopes);
	}
	
	public RedEnvelopes getRedEnvelopesByUuid(String uuid) {
		return redEnvelopesMapper.selectByPrimaryKey(uuid);
	}
	
	public List<RedEnvelopes> getPageRedEnvelopes(RedEnvelopesExample redEnvelopesExample) {
		return redEnvelopesMapper.selectPage(redEnvelopesExample);
	}
	
	public int countRedEnvelopes(RedEnvelopesExample redEnvelopesExample) {
		return redEnvelopesMapper.countByExample(redEnvelopesExample);
	}
	public RedEnvelopes getRedEnvelopes(String questionUuid,String phone){
		return redEnvelopesExMapper.selectRedEnvelopesByPhone(phone, questionUuid);
	}
	public void updateUserAndAddRedEnvelopes(User user,User user1,RedEnvelopes redEnvelopes){
		if(user!=null){
			userMapper.updateByPrimaryKeySelective(user);
		}
		if(user1!=null){
			userMapper.updateByPrimaryKeySelective(user1);
			
		}
		if(redEnvelopes!=null){
			redEnvelopesMapper.insertSelective(redEnvelopes);
		}
		if(user!=null&&user1!=null&&redEnvelopes!=null){
			Date date = new Date();
			String uuid=UUIDGenerator.getUUID();
			String uuid3 = redEnvelopes.getUuid();
			Double money = redEnvelopes.getMoney();
			
			//红包流水 发送者
			UserDealRecord userDealRecord = new UserDealRecord();
			userDealRecord.setUuid(uuid);
			userDealRecord.setUserId(user1.getPhoneNumber());
			userDealRecord.setBusinessNo(uuid3);
			userDealRecord.setCreateDate(date);
			userDealRecord.setSum(money);
			userDealRecord.setPaySucTime(date);
			userDealRecord.setGoodsType(PayTypeUtil.GOODSTYPE_ENVELOPES);
			userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
			userDealRecord.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
			userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
			//接受者
			String uuid2=UUIDGenerator.getUUID();
			UserDealRecord userDealRecord2 = new UserDealRecord();
			userDealRecord2.setUuid(uuid2);
			userDealRecord2.setUserId(user.getPhoneNumber());
			userDealRecord2.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
			userDealRecord2.setBusinessNo(uuid3);
			userDealRecord2.setCreateDate(date);
			userDealRecord2.setSum(money);
			userDealRecord2.setPaySucTime(date);
			userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_ENVELOPES);
			userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
			userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecordMapper.insertSelective(userDealRecord);
			userDealRecordMapper.insertSelective(userDealRecord2);
		}
	}
	/**
	 * 公司发红包
	 * @param questionUuid
	 * @param phoneNumber
	 * @param redType
	 * @return
	 */
	public Object addSendRedEnvelopes(String questionUuid,String phoneNumber,String redType){
		RedEnvelopes redEnvelopes = redEnvelopesExMapper.selectRedEnvelopesByPhone(phoneNumber, questionUuid);
		SendRedResponse sendRedResponse=new SendRedResponse();
		try {
			
			if(redType!=null&&!redType.equals("")){
				RedEnvelopes envelopes = new RedEnvelopes();
				String uuid = UUIDGenerator.getUUID();
				
				
				Date date = new Date();
				envelopes.setSendDate(date);
				envelopes.setSendPhoneNum(PayTypeUtil.COMPANY_ACCPUNT);
				envelopes.setUserPhoneNum(phoneNumber);
				envelopes.setUuid(uuid);
				String uuid1=UUIDGenerator.getUUID();//公司流水
				//红包流水
				UserDealRecord userDealRecord = new UserDealRecord();
				userDealRecord.setUuid(uuid1);
				userDealRecord.setUserId(PayTypeUtil.COMPANY_ACCPUNT);
				userDealRecord.setAccountType(PayTypeUtil.ACCOUNTTYPE_BUSINESS);
				userDealRecord.setBusinessNo(uuid);
				userDealRecord.setCreateDate(date);
				userDealRecord.setGoodsType(PayTypeUtil.GOODSTYPE_ENVELOPES);
				userDealRecord.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
				userDealRecord.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
				
				UserDealRecord userDealRecord2 = new UserDealRecord();//用户流水
				String uuid2=UUIDGenerator.getUUID();
				userDealRecord2.setUuid(uuid2);
				userDealRecord2.setUserId(phoneNumber);
				userDealRecord2.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
				userDealRecord2.setBusinessNo(uuid);
				userDealRecord2.setCreateDate(date);
				userDealRecord2.setPaySucTime(date);
				userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_ENVELOPES);
				userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
				userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
				if(redType.equals(PayTypeUtil.REDENVELPES_TTK)){
					//偷偷看红包
					if(redEnvelopes!=null){
						String redStatus = redEnvelopes.getRedStatus();
						Double money = redEnvelopes.getMoney();
						if(redStatus!=null&&!redStatus.equals("")){
							if(redStatus.equals(PayCommonUtil.PAYSUCCESS_STATUS)){
								//红包已发 并已领
								sendRedResponse.setSend(false);
							}else if (redStatus.equals(PayCommonUtil.PAYPENDING_STATUS)) {
								//红包已发 未领
								sendRedResponse.setSend(true);
								sendRedResponse.setMoney(money);
							}else {
								sendRedResponse.setSend(false);
							}
						}else {
							//数据错误
							sendRedResponse.setSend(false);
						}
						
					}else {
						//随机发一个红包
						//Question question = questionMapper.selectByPrimaryKey(questionUuid);
						QuestionUserKey questionUserKey = new QuestionUserKey();
						questionUserKey.setPhoneNumber(phoneNumber);
						questionUserKey.setQuestionUuid(questionUuid);
						QuestionUserKey userKey = questionUserService.getQuestionUserKeys(questionUserKey);
						if(userKey!=null){
							//String phoneNum = question.getPhoneNum();
							
							/*	if(phone.equals(phoneNum)){
									sendRedResponse.setSend(false);
								}else {*/
									double money=0.1;
									RedEnvelopesExample example = new RedEnvelopesExample();
									Criteria criteria = example.createCriteria();
									criteria.andUserPhoneNumEqualTo(phoneNumber);
									criteria.andRedTypeEqualTo(PayTypeUtil.REDENVELPES_TTK);
									criteria.andSendDateBetween(MoneyRandom.getBeforeDateTime(), MoneyRandom.getAfterDateTime());
									int i = redEnvelopesMapper.countByExample(example);
									if(i<2){
										//money = MoneyRandom.getEveryDayMoney();
										//money = MoneyRandom.getMoney();
										money=MoneyRandom.getTwoMoney();
									}else {
										//money = MoneyRandom.getMoney();
										money = MoneyRandom.getTwoMoney();
									}
									envelopes.setRedType(PayTypeUtil.REDENVELPES_TTK);
									envelopes.setMoney(money);
									envelopes.setRedStatus(PayCommonUtil.PAYPENDING_STATUS);
									envelopes.setQuestionUuid(questionUuid);
									envelopes.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
									userDealRecord.setSum(money);
									
									userDealRecord.setStatus(PayCommonUtil.PAYPENDING_STATUS);
									redEnvelopesMapper.insertSelective(envelopes);
									userDealRecordMapper.insertSelective(userDealRecord);
									sendRedResponse.setMoney(money);
									sendRedResponse.setSend(true);
								//}
							}else {
								sendRedResponse.setSend(false);
							}
						}
					
					
				}else if(redType.equals(PayTypeUtil.REDENVELPES_REGISTER)){
					
					RedEnvelopesExample redEnvelopesExample = new RedEnvelopesExample();
					Criteria createCriteria = redEnvelopesExample.createCriteria();
					createCriteria.andUserPhoneNumEqualTo(phoneNumber);
					createCriteria.andRedStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
					createCriteria.andRedTypeEqualTo(redType);
					int i = redEnvelopesMapper.countByExample(redEnvelopesExample);
					if (i>0) {
						sendRedResponse.setSend(false);
						return sendRedResponse;
					}
					
					//double money = MoneyRandom.registAndShareMoney();
					double money=0.66;
					envelopes.setRedType(PayTypeUtil.REDENVELPES_REGISTER);
					envelopes.setMoney(money);
					envelopes.setRedStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					envelopes.setPayType(PayTypeUtil.PAYTYPE_COMPANYENVELOPES);
					envelopes.setReceiveDate(date);
					userDealRecord.setPaySucTime(date);
					userDealRecord.setSum(money);
					userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					userDealRecord2.setSum(money);
					userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					
					User user = userMapper.selectByPrimaryKey(phoneNumber);
					if(user!=null){
						User user2 = new User();
						user2.setPhoneNumber(phoneNumber);
						
						Double balance = user.getBalance();
						user2.setBalance(balance+money);
						userMapper.updateByPrimaryKeySelective(user2);
					}
					
					
					redEnvelopesMapper.insertSelective(envelopes);
					userDealRecordMapper.insertSelective(userDealRecord);
					userDealRecordMapper.insertSelective(userDealRecord2);
					sendRedResponse.setMoney(money);
					sendRedResponse.setSend(true);
				}else if(redType.equals(PayTypeUtil.REDENVELPES_SHARE)){
					//作废
//					RedEnvelopesExample example = new RedEnvelopesExample();
//					Criteria criteria = example.createCriteria();
//					criteria.andUserPhoneNumEqualTo(phone);
//					criteria.andRedTypeEqualTo(PayTypeUtil.REDENVELPES_SHARE);
//					int i = redEnvelopesMapper.countByExample(example);
//					if(i<1){
//						//double money = MoneyRandom.registAndShareMoney();
//						double money=0.66;
//						envelopes.setRedType(PayTypeUtil.REDENVELPES_SHARE);
//						envelopes.setMoney(money);
//						envelopes.setRedStatus(PayCommonUtil.PAYSUCCESS_STATUS);
//						envelopes.setReceiveDate(date);
//						userDealRecord.setSum(money);
//						userDealRecord.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
//						userDealRecord.setPaySucTime(date);
//						userDealRecord2.setSum(money);
//						userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
//						User user = userMapper.selectByPrimaryKey(phone);
//						if(user!=null){
//							User user2 = new User();
//							user2.setPhoneNumber(phone);
//							Double balance = user.getBalance();
//							user2.setBalance(balance+money);
//							userMapper.updateByPrimaryKeySelective(user2);
//						}
//						redEnvelopesMapper.insertSelective(envelopes);
//						userDealRecordMapper.insertSelective(userDealRecord);
//						userDealRecordMapper.insertSelective(userDealRecord2);
//						sendRedResponse.setMoney(money);
//						sendRedResponse.setSend(true);
//					}else {
//						sendRedResponse.setSend(false);
//					}
//					
					
				}else {
					if(redType.equals(PayTypeUtil.REDENVELPES_SHARE_ARTICLE) 
							|| redType.equals(PayTypeUtil.REDENVELPES_SHARE_SECRETLY)
							|| redType.equals(PayTypeUtil.REDENVELPES_SHARE_QUESTION)
							|| redType.equals(PayTypeUtil.REDENVELPES_PERSONAL_INFO)){
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("userPhoneNum", phoneNumber);
						map.put("redType", redType);
						//判断是否已经发过补全个人信息红包
						if(redType.equals(PayTypeUtil.REDENVELPES_PERSONAL_INFO)){
							List<RedEnvelopes> selectByMap = redEnvelopesExMapper.selectByMap(map);
							if(selectByMap != null && selectByMap.size() > 0){
								sendRedResponse.setSend(false);
								return sendRedResponse;
							}
						}
						map.put("oneDay", 1);
						List<RedEnvelopes> selectByMap = redEnvelopesExMapper.selectByMap(map);
						if(selectByMap.size() < 3){
							RedEnvelopes redE = new RedEnvelopes();
							double redMoney = 0;
							if(redType.equals(PayTypeUtil.REDENVELPES_SHARE_ARTICLE)){
								redMoney = PayTypeUtil.REDENVELOPES_SHARE_ARTICLE_QAMONEY;
							}else if(redType.equals(PayTypeUtil.REDENVELPES_SHARE_SECRETLY)){
								redMoney = PayTypeUtil.REDENVELOPES_SHARE_BUY_SECRETLY_QAMONEY;
							}else if(redType.equals(PayTypeUtil.REDENVELPES_SHARE_QUESTION)){
								redMoney = PayTypeUtil.REDENVELOPES_SHARE_QUESTIONS_ACCEPTED_QAMONEY;
							}else if(redType.equals(PayTypeUtil.REDENVELPES_PERSONAL_INFO)){
								redMoney = PayTypeUtil.REDENVELOPES_COMPLETION_PERSONAL_DATA_QAMONEY;
							}else{
								sendRedResponse.setSend(false);
								return sendRedResponse;
							}
							redE.setMoney(redMoney);//金额
							redE.setUserPhoneNum(phoneNumber);//领取红包人的用户主键
							redE.setRedType(redType);//红包类型
//							redE.setQuestionUuid(questionUuid);//业务主键
							this.addQACardRedEnvelopes(redE, null);
							sendRedResponse.setMoney(redMoney);
							sendRedResponse.setSend(true);
						}else{
							sendRedResponse.setSend(false);
						}
					}else {
						sendRedResponse.setSend(false);
					}
				}
			}else {
				sendRedResponse.setSend(false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
		return sendRedResponse;
	}
	
	public List<RedEnvelopes> getRedListByPhone(PagePhone pagePhone){
		return redEnvelopesExMapper.selectPageByPhone(pagePhone);
	}
	/**
	 * 发红包后操作
	 * @param red
	 * @param user
	 * @param userDealRecord 
	 * @param userDealRecord1 
	 * @param userDealRecord3 
	 * @param userDealRecord2 
	 */
	public void updateAfterSendRedbag(RedEnvelopes red, User user, UserDealRecord userDealRecord, UserDealRecord userDealRecord1, UserDealRecord userDealRecord2, UserDealRecord userDealRecord3) {
		redEnvelopesMapper.updateByPrimaryKeySelective(red);
		log.info("REDBAG 修改红包业务状态："+JsonUtil.toJson(red));
		userMapper.updateByPrimaryKeySelective(user);
		log.info("REDBAG 红包加入余额："+JsonUtil.toJson(user));
		userDealRecordMapper.insert(userDealRecord);
		log.info("REDBAG 红包支付流水："+JsonUtil.toJson(userDealRecord));
		userDealRecordMapper.insert(userDealRecord1);
		log.info("REDBAG 公司收入流水："+JsonUtil.toJson(userDealRecord1));
		userDealRecordMapper.insert(userDealRecord2);
		log.info("REDBAG 公司支出流水："+JsonUtil.toJson(userDealRecord2));
		userDealRecordMapper.insert(userDealRecord3);
		log.info("REDBAG 用户收入流水："+JsonUtil.toJson(userDealRecord3));
	}
	
	/**
	 * 文章红包总数 总额
	 * @param id
	 * @return
	 */
	public CountAndSumMoney getCountAndSumMoney(String id){
		return redEnvelopesExMapper.selectCountAndSumMoney(id);
	}
	/**
	 * 发红包人的头像
	 * @param id
	 * @return
	 */
	public List<String> getUserHeadImages(String id){
		return redEnvelopesExMapper.selectUserHeadImages(id);
	}
	
	public List<RedEnvelopesArticleUser> getRedEnvelopesArticleUsers(PagePhone pagePhone){
		return redEnvelopesExMapper.selectAllUserRedEnvelopes(pagePhone);
	}
	/**
	 * 1.增加问答卡红包记录
	 * 2.用户问答卡余额增加
	 * 3.记录双向流水
	 * @param redEnvelopes {money:金额,userPhoneNum:用户主键,redType:红包类型}
	 */
	public void addQACardRedEnvelopes(RedEnvelopes redEnvelopes,Long userSrc){
		redEnvelopes.setUuid(IdGen.uuid());
		redEnvelopes.setSendPhoneNum(Const.JSBUSERID);//发送红包的账号（公司账户ID）
		redEnvelopes.setSendDate(new Date());//发送日期
		redEnvelopes.setReceiveDate(redEnvelopes.getSendDate());//发送日期
		redEnvelopes.setRedStatus("0");//红包状态： 0 已领 1 未领
		redEnvelopes.setPayType(PayTypeUtil.PAYTYPE_QACARDBALANCE);//支付类型：0 余额支付 1会员卡支付 2 企业会员卡支付 3微信支付 7问答卡支付
		//增加已领取红包
		this.addRedEnvelopes(redEnvelopes);
		User user = new User();
		user.setPhoneNumber(redEnvelopes.getUserPhoneNum());
		user.setQACardBlance(redEnvelopes.getMoney());
		//当绑定问答卡时，更新用户渠道
		if(userSrc != null && !"".equals(userSrc)){
			user.setUserSrc(userSrc);
		}
		//增加用户问答卡金额
		userService.updateUserQACardBlance(user);
		//双向流水参数
		Map<String, Object> inAnOutRows = new HashMap<String, Object>();
		inAnOutRows.put("in",PayTypeUtil.ACCOUNTTYPE_PERSONAL);
		inAnOutRows.put("out",PayTypeUtil.ACCOUNTTYPE_BUSINESS);
		//记录双向流水
		userDealRecordService.userdealRecordCommonRunning(redEnvelopes.getUserPhoneNum(), redEnvelopes.getUuid(),
				redEnvelopes.getPayType(), redEnvelopes.getMoney(), 
				PayTypeUtil.GOODSTYPE_ENVELOPES, "问答卡红包", inAnOutRows);
	}
	/**
	 * 查询红包
	 * @param params {userPhoneNum:用户手机号,redType:红包类型}
	 */
	public List<RedEnvelopes> selectRedEnvelopesByParams(Map<String, Object> params){
		//增加已领取红包
		return redEnvelopesExMapper.selectByMap(params);
	}
	/**
	 * 查询红包
	 * @param params {userPhoneNum:用户手机号,redType:红包类型}
	 */
	public Double countRedEnvelopesByParams(Map<String, Object> params){
		return redEnvelopesExMapper.countByMap(params);
	}
}
